package com.csw.zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

//主备切换
public class Demo02zk {
    ZooKeeper zk;
    @Before
    public void init()throws Exception{
        zk = new ZooKeeper("master:2181,node1:2181,node2:2181",
                3000, null);
    }
    @Test//创建
    public void create()throws Exception{
        zk.create("/hadoop",//节点
                "hadoop".getBytes(),//数据
                ZooDefs.Ids.OPEN_ACL_UNSAFE,//节点权限
                CreateMode.EPHEMERAL);//临时节点

        Thread.sleep(10000);//睡眠10秒
    }
    @Test
    public void watcher()throws Exception{
        /**
         * 观察者监听节点状态，节点发生变化，zk通知客户端执行回调函数
         * 创建客户端
         */
        zk.getChildren("/hadoop", new Watcher() {
            public void process(WatchedEvent watchedEvent) {
                System.out.println(watchedEvent);
                System.out.println("主节点故障了");
                System.out.println("备用节点切换成active状态");
            }
        });
        while (true){}
    }
    @After
    public void close()throws Exception{
        zk.close();
    }
}
